﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using TemplateFoundation.Exceptions;

namespace TemplateFoundation.Handlers.EPiServerCustomization
{
    /// <summary>
    /// Replaces the standard logo image on the EPiServer login page
    /// </summary>
    public class LoginLogoHandler : IHttpHandler
    {
        private readonly byte[] _image;

        /// <summary>
        /// Instantiates the handler and loads the image
        /// </summary>
        public LoginLogoHandler()
        {
            var file = GetType().Assembly.GetManifestResourceStream("TemplateFoundation.Images.EPiServerCMSLogo-Util.png");
            if (file==null)
            {
                throw new TemplateFoundationException("Unable to load embedded login logo image");
            }

            using (var stream = new MemoryStream())
            {
                using(var image = Image.FromStream(file))
                {
                    image.Save(stream, ImageFormat.Png);

                    _image = stream.ToArray();

                    // Clean up
                    stream.Close();
                    stream.Dispose();
                    image.Dispose();                   
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.</returns>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";
            context.Response.BinaryWrite(_image);
            context.Response.End();
        }
    }
}
